<template>
  <main class="container">
    <div class="inputCity">
      <input
        type="text"
        placeholder="请输入城市名称"
        v-model.trim="content"
        @keyup.enter="handleSearch"
        @blur="handleSearch"
        @keyup.space="handleSpaceKey"
      />
      <ul :style="{ display: show ? 'block' : 'none' }">
        <li
          v-if="
            CityData &&
            CityData.geocodes &&
            CityData.geocodes.length > 0 &&
            CityData.geocodes[0].district.length > 0
          "
          @click="
            handleClick(
              CityData.geocodes[0].adcode,
              CityData.geocodes[0].district
            )
          "
        >
          {{ CityData.geocodes[0].district }}
        </li>
        <li
          v-else-if="
            CityData &&
            CityData.geocodes &&
            CityData.geocodes.length > 0 &&
            CityData.geocodes[0].city.length == 0
          "
          @click="
            handleClick(
              CityData.geocodes[0].adcode,
              CityData.geocodes[0].province
            )
          "
        >
          {{ CityData.geocodes[0].province }}
        </li>
        <li
          v-else-if="
            CityData && CityData.geocodes && CityData.geocodes.length > 0
          "
          @click="
            handleClick(CityData.geocodes[0].adcode, CityData.geocodes[0].city)
          "
        >
          {{ CityData.geocodes[0].city }}
        </li>
      </ul>
    </div>
    <h2 v-if="savedCities.length === 0">
      暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
    </h2>
    <div class="list-container" v-else>
      <div class="list-item" v-for="(city, index) in savedCities" :key="index">
        <div class="list-item-info">
          <h3>{{ city.name }}</h3>
          <span>{{ city.temperature }}度</span>
        </div>
        <div class="list-item-button">
          <button @click="handleWatch(city)">查看</button>
          <button @click="handleDelete(index)">删除</button>
        </div>
      </div>
    </div>
    <h2 class="weather-title">近期天气</h2>
    <WeatherInfo></WeatherInfo>
  </main>
</template>

<script setup>
import { ref, watch, inject, computed } from 'vue'
import { useRouter } from 'vue-router'

import WeatherInfo from './WeatherInfo.vue'
import { getCityData } from '@/API'

const content = ref('')
const show = ref(false)
const router = useRouter()
const CityData = ref({})

// 注入保存的城市列表
const savedCities = inject('savedCities', ref([]))
// 注入已访问城市列表
const visitedCities = inject('visitedCities', ref([]))

console.log(savedCities)

const handleSearch = async () => {
  if (content.value) {
    const data = await getCityData(content.value)
    if (data) {
      CityData.value = data
      // console.log(CityData)
      show.value = true //控制ul显示
    }
  }
}
// 处理空格键事件
const handleSpaceKey = (event) => {
  // 阻止空格键的默认行为
  event.preventDefault()
  // 触发搜索
  handleSearch()
}

// 处理查看
const handleWatch = (city) => {
  if (city && city.adcode && city.name) {
    // 将该城市标记为已访问
    const exists = visitedCities.value.some(
      (visitedCity) =>
        visitedCity.name === city.name && visitedCity.adcode === city.adcode
    )
    if (!exists) {
      visitedCities.value.push({
        name: city.name,
        adcode: city.adcode,
      })
    }

    // 跳转到对应城市的天气页面
    router.push({
      path: `/${city.adcode}`,
      query: {
        search: city.name,
      },
    })
  }
}

// 处理删除按钮点击事件
const handleDelete = (index) => {
  if (index >= 0 && index < savedCities.value.length) {
    savedCities.value.splice(index, 1)
  }
}
// 监听content的变化
watch(content, (newContent, oldContent) => {
  if (!newContent) {
    CityData.value = {}
    show.value = false
  }
})

const handleClick = (adcode, cityName) => {
  if (adcode && cityName) {
    router.push({
      path: `/${adcode}`,
      query: {
        search: cityName,
      },
    })
  }
}
</script>

<style lang="scss" scoped>
.container {
  color: white;
  max-width: 1536px;
  width: 100%;
  margin-right: auto;
  margin-left: auto;
  padding-right: 10rem;
  padding-left: 10rem;
  .inputCity {
    position: relative;
    padding-top: 1rem;
    margin-bottom: 2rem;
    input {
      width: 100%;
      background-color: transparent;
      padding: 0.5rem 0.25rem;
      border-bottom-width: 1px;
      font-family: inherit;
      font-size: 100%;
      font-weight: inherit;
      line-height: inherit;
      color: inherit;
      border: none;
      border-bottom: 1px solid white;
      &::placeholder {
        color: #ccc;
      }
      &:focus {
        color: white;
        border: none;
        outline: none;
        box-shadow: 0 10px 15px -3px rgb(0, 0, 0, 0.1);
      }
    }
    ul {
      display: none;
      position: absolute;
      list-style: none;
      width: 100%;
      top: 62px;
      padding: 0.5rem 0.25rem;
      background-color: rgb(0 78 113);
      li {
        padding: 0.5rem 0;
        cursor: pointer;
      }
    }
  }
  h2 {
    font-weight: inherit;
    font-size: inherit;
    text-align: center;
    margin-top: 5rem;
  }
  .list-container {
    margin-top: 2.5rem;
    max-height: 300px;

    .list-item {
      display: flex;
      justify-content: space-between;
      line-height: 1.6rem;
      .list-item-info {
        display: flex;
        justify-content: space-between;
        width: 100%;

        margin-bottom: 1rem;
        padding: 0.5rem 1rem;
        background-color: rgb(0 78 113);
        transition-duration: 0.3s;
        cursor: pointer;

        h3 {
          font-size: inherit;
          font-weight: inherit;
        }
      }
      .list-item-button {
        display: flex;
        margin-bottom: 1rem;
        gap: 0.5rem;
        button {
          display: none;
          text-align: center;
          background-color: rgb(234 179 8);
          width: 80px;
          cursor: pointer;
          border: none;
          color: white;
          font-size: inherit;
        }
      }
      &:hover {
        .list-item-info {
          width: 80%;
        }
        .list-item-button button {
          display: block;
        }
      }
    }
  }
  .weather-title {
    font-weight: inherit;
    font-size: inherit;
    text-align: left;
    margin-top: 1.5rem;
  }
}
</style>
